<template>
  <div class="wik-tabs">
    <div class="wik-tabs-wrap">
      <div
        class="wik-tabs-item"
        :class="{ 'wik-tabs-item_active': index === currentIndex }"
        v-for="(item, index) in list"
        :key="index"
        :ref="setWidth"
        @click="changeHandle(index, item)"
      >
        <template v-if="slots[item.key]">
          <slot :name="item.key" />
        </template>
        <template v-else>
          {{ item.name }}
        </template>
      </div>
      <div class="wik-tabs-line" :style="`width:${widths[currentIndex]}px; transform:translateX(${left}px)`"></div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, nextTick, computed, useSlots } from "vue";
type Tabs = {
  name: string;
  key: string;
};

const { active } = defineProps({
  list: {
    type: Array<Tabs>,
    default: () => []
  },
  active: {
    type: Number,
    default: 0
  }
});

const emits = defineEmits(["change"]);
const slots = useSlots();

const currentIndex = ref<number>(active);

const widths = ref<Array<number>>([]);

const left = computed(() => {
  return widths.value.reduce((pre, cur, index) => {
    return index <= currentIndex.value - 1 ? pre + cur + 16 : pre;
  }, 0);
});

const setWidth = (el: any) => {
  nextTick(() => {
    widths.value.push(el?.offsetWidth);
  });
};
const changeHandle = (index: number, item: Tabs) => {
  currentIndex.value = index;
  emits("change", { index, item });
};

onMounted(() => {});
</script>
<style lang="scss">
.wik-tabs {
  box-sizing: border-box;
  height: 36px;
  overflow: hidden;
  border-bottom: 1px solid #f4f4f4;
  &-wrap {
    position: relative;
    display: flex;
    justify-content: flex-start;
    height: 100%;
    overflow-y: hidden;
  }
  &-item {
    flex-grow: 0;
    flex-shrink: 0;
    height: 36px;
    padding: 0 16px;
    margin-right: 16px;
    line-height: 36px;
    text-align: center;
    cursor: pointer;
    &_active {
      color: $primary-color;
    }
  }
  &-line {
    position: absolute;
    bottom: 0;
    height: 1px;
    background: $primary-color;
    transition: all 0.3s;
  }
}
</style>
